var express = require('express');
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session')
var http = require("http");

var app = express();
app.use(bodyParser.json());
app.use(cookieParser());
app.use(session({ secret: '1234567890QWERTY', cookie: { maxAge: 600000 } }));

app.scHost = "localhost";
app.scPort = 10000;
app.scServiceName = "WebServiceServiceCenter.asmx";
app.scUsername = "ppuser";
app.scPassword = "123";

app._post = function (methodName, data, completed) {
    var dataString = JSON.stringify(data);
    var option = {
        method: "POST",
        host: app.scHost,
        port: app.scPort,
        path: "/" + app.scServiceName + "/" + methodName,
        headers: {
            "Content-Type": 'application/json; charset=UTF-8'
        }
    };
    if (app.cookie) {
        option.headers["Cookie"] = app.cookie;
    }
    var req = http.request(option, function (res) {
        res.setEncoding('utf8');
        var body = "";
        res.on('data', function (data) {
            body += data;
        });
        res.on('end', function () {
            if (res.headers["set-cookie"]) {
                app.cookie = res.headers["set-cookie"];
            }
            var data = JSON.parse(body);
            if (data.d) {
                data = data.d;
            }
            completed(data);
        });
    });
    req.on('error', (e) => {
        console.log(`problem with request: ${e.message}`);
    });
    req.write(dataString);
    req.end();
}

app._login = function (completed) {
    app._post("Login", { username: app.scUsername, password: app.scPassword }, completed);
}

app._getGuid = function (completed) {
    app._post("GetGuid", {}, completed);
}

app._getGuids = function (data, completed) {
    app._post("GetGuids", data, completed);
}

app._invokeByJsonInvokeArgument = function (data, completed) {
    app._post("InvokeByJsonInvokeArgument", data, function (result) {
        if (result.Message && result.Message === "Session不存在，请登陆。") {
            app._login(function () {
                app._post("InvokeByJsonInvokeArgument", data, function (result) {
                    completed(result);
                });
            });
        }
        else {
            completed(result);
        }
    });
}

app.post('/login', function (req, res) {
    app._invokeByJsonInvokeArgument({
        invokeArgument: {
            ApplicationNo: 'Pp',
            ServiceNo: 'user',
            OperationNo: 'queryByUsernameAndPassword',
            Arguments: [JSON.stringify(req.body.username), JSON.stringify(req.body.password)]
        }
    }, function (result) {
        var user = result.Result;
        if (user !== null) {
            req.session.user = user;
        }
        res.send(200, result);
    });
});

app.post('/getGuid', function (req, res) {
    if (req.session.user) {
        app._getGuid(function (result) {
            res.send(200, result);
        });
    }
    else {
        res.send(200, { error: 'login-timeout' });
    }
});

app.post('/getGuids', function (req, res) {
    if (req.session.user) {
        app._getGuids(req.body, function (result) {
            res.send(200, result);
        });
    }
    else {
        res.send(200, { error: 'login-timeout' });
    }
});

app.post('/invokeByJsonInvokeArgument', function (req, res) {
    if (req.session.user) {
        app._invokeByJsonInvokeArgument(req.body, function (result) {
            res.send(200, result);
        });
    }
    else {
        res.send(200, { error: 'login-timeout' });
    }
});

var server = app.listen(13001, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('Example app listening at http://%s:%s', host, port);
});